﻿using System;
using System.IO;
// 
//=====================================================================================
// Repository: https://gitee.com/putzone/fofasearch
//=====================================================================================
//
using System.Net;
using System.Text;

namespace FofaLib
{
    class HttpHelper
    {
        public static HttpResult Get(string url)
        {
            HttpResult httpResult = new HttpResult()
            {
                Error = false,
                Result = string.Empty
            };
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Timeout = 120000;
            try
            {
                using (StreamReader reader = new StreamReader(((HttpWebResponse)req.GetResponse()).GetResponseStream(), Encoding.UTF8))
                {
                    httpResult.Result = reader.ReadToEnd();
                }
            }
            catch (WebException wex)
            {
                if(wex.Status == WebExceptionStatus.ProtocolError)
                {
                    using (StreamReader reader = new StreamReader(((HttpWebResponse)wex.Response).GetResponseStream(), Encoding.UTF8))
                    {
                        httpResult.Result = reader.ReadToEnd();
                    }
                }
                else
                {
                    httpResult.Error = true;
                    httpResult.Result = wex.Message;
                }
            }
            catch (Exception ex)
            {
                httpResult.Error = true;
                httpResult.Result = ex.Message;
            }
            return httpResult;
        }
    }

    struct HttpResult
    {
        public bool Error;
        public string Result;
    }
}
